package org.projectname.web.admin.manager;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.hishenframework.core.data.jdbc.template.DataPaging;
import org.hishenframework.core.web.menu.MenuItem;
import org.projectname.entity.manager.Role;
import org.projectname.entity.manager.User;
import org.projectname.entity.manager.UserRole;
import org.projectname.service.admin.manager.RoleService;
import org.projectname.service.admin.manager.UserRoleService;
import org.projectname.service.admin.manager.UserService;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(UserController.PATH)
@MenuItem(type = "账号管理", label = "账号管理", order = 97)
public class UserController {

	public final static String PATH = "/admin/manager/user";
	public final static String RELOAD = "redirect:" + PATH;

	@Resource
	private UserService userService;

	@Resource
	private UserRoleService userRoleService;

	@Resource
	private RoleService roleService;

	@RequestMapping
	public String list(Model model,
			@ModelAttribute DataPaging<User> dataPaging, String username,
			Date from, Date to) {
		userService.search(dataPaging, username, from, to);
		model.addAttribute("userRoles", userRoleService.getAll());
		model.addAttribute("roles", roleService.getAll());
		return PATH + "/list";
	}

	@RequestMapping("/edit/{id}")
	public String edit(@PathVariable int id, Model model) {
		List<Role> roles = roleService.getAll();
		List<UserRole> userRoles = userRoleService.getByUserId(id);
		Iterator<Role> iteratorOfRoles = roles.iterator();
		while (iteratorOfRoles.hasNext()) {
			Role tempRole = iteratorOfRoles.next();
			Iterator<UserRole> iteratorOfUserRoles = userRoles.iterator();
			while (iteratorOfUserRoles.hasNext()) {
				UserRole tempUserRole = iteratorOfUserRoles.next();
				if (tempUserRole.getRoleId() == tempRole.getId()) {
					tempRole.setUsed(true);
				}
			}
		}
		model.addAttribute("roles", roles);
		model.addAttribute("user", userService.get(id));
		return PATH + "/edit";
	}

	@RequestMapping("/create")
	public String create(Model model) {
		model.addAttribute("roles", roleService.getAll());
		return PATH + "/create";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(@Valid User user, UserRole entity,
			BindingResult bindingResult) {
		if (!bindingResult.hasErrors()) {
			user.setPassword(new Md5PasswordEncoder().encodePassword(
					user.getPassword(), user.getUsername()));
			int id = (int) userService.save(user);
			if (entity.getRoleIds() == null) {
				return RELOAD;
			}
			Iterator<Integer> iteratorOfRoleIds = entity.getRoleIds()
					.iterator();
			while (iteratorOfRoleIds.hasNext()) {
				entity.setUserId(id);
				entity.setRoleId(iteratorOfRoleIds.next());
				userRoleService.save(entity);
			}
		}
		return RELOAD;
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(@Valid User user, UserRole entity,
			BindingResult bindingResult) {
		if (!bindingResult.hasErrors()) {
			if(user.getPassword() == null || user.getPassword().length() == 0){
				userService.updateUsername(user);
			}else{
				user.setPassword(new Md5PasswordEncoder().encodePassword(
						user.getPassword(), user.getUsername()));
				userService.update(user);
			}
			userRoleService.deleteByUserId(entity.getUserId());
			if (entity.getRoleIds() == null) {
				return RELOAD;
			}
			Iterator<Integer> iteratorOfRoleIds = entity.getRoleIds()
					.iterator();
			while (iteratorOfRoleIds != null && iteratorOfRoleIds.hasNext()) {
				entity.setRoleId(iteratorOfRoleIds.next());
				userRoleService.save(entity);
			}
		}
		return RELOAD;
	}

	@RequestMapping("/delete/{id}")
	public String delete(@PathVariable int id) {
		userRoleService.deleteByUserId(id);
		userService.delete(id);
		return RELOAD;
	}
}
